package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.heima.admin.mapper.LoginMapper;
import com.heima.admin.service.LoginService;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.Map;

@Service
public class LoginServiceImpl extends ServiceImpl<LoginMapper, AdUser> implements LoginService {
    @Override
    public ResponseResult login(AdUserDto dto) {

    //检查数据
        if (StringUtils.isEmpty(dto.getName())||StringUtils.isEmpty(dto.getPassword()))
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);

    //根据用户名查询数据库获取用户信息
        QueryWrapper<AdUser> wrapper = new QueryWrapper<>();
        wrapper.eq("name",dto.getName());
        List<AdUser> list = list(wrapper);
        if (list==null||list.size()==0||list.get(0)==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"用户名不存在");
        }
        AdUser adUser = list.get(0);
        String pswd = DigestUtils.md5DigestAsHex((dto.getPassword() + adUser.getSalt()).getBytes());

        //用dto的密码生成密文与数据库查询的密码比较
        if (adUser.getPassword().equals(pswd)){
          Map<String, Object> map = Maps.newHashMap();
            //生成token令牌，存入heands中
            String token = AppJwtUtil.getToken(adUser.getId().longValue());

            adUser.setPassword(""); //返回前台是不显示密码   保护用户信息
            adUser.setSalt("");     //返回前台不显示盐      保护用户信息

            map.put("token",token);
            map.put("User",adUser);

            return ResponseResult.okResult(map);
        }

        return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户或密码错误");
    }
}
